<template>
  <div class="model-page">
    <!-- 操作栏 -->
    <header class="operate-panel">
      <div class="header-lf">
        <span> 水厂作业空间 3d模型可视化编辑系统 </span>
        <span> 当前Three.js版本:{{ THREE.REVISION }} </span>
      </div>
      <div class="header-lr">
        <el-space>
          <el-button
            type="primary"
            size="small"
            icon="Film"
            @click="onSubmitData"
          >
            提交
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Document"
            @click="goBack"
            >返回</el-button
          >

          <el-dropdown trigger="click" size="small">
            <el-button type="primary" size="small" icon="Download">
              下载/导出<el-icon class="el-icon--right"></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="onDownloadCover"
                  >下载封面</el-dropdown-item
                >
                <el-dropdown-item @click="onExportModleFile('glb')"
                  >导出模型(.glb)格式</el-dropdown-item
                >
                <el-dropdown-item @click="onExportModleFile('gltf')"
                  >导出模型(.gltf)格式</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown placement="bottom-start" trigger="click" size="small">
            <el-button type="primary" size="small" icon="Pointer">
              快捷键<el-icon class="el-icon--right"></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="Delete"
                  >删除模型/管道（Delete）</el-dropdown-item
                >
                <el-dropdown-item command="l">连接管道（l）</el-dropdown-item>

                <el-dropdown-item command=" " divided
                  >是否启用控制器（空格键）</el-dropdown-item
                >
                <el-dropdown-item command="w"
                  >设置变换模式为translate（w）</el-dropdown-item
                >
                <el-dropdown-item command="e"
                  >设置变换模式为rotate（e）</el-dropdown-item
                >
                <el-dropdown-item command="r"
                  >设置变换模式为scale（r）</el-dropdown-item
                >
                <el-dropdown-item command="Shift"
                  >按固定步幅变换（按住Shift）</el-dropdown-item
                >

                <el-dropdown-item command="+" divided
                  >增加手柄UI的大小（+/=）</el-dropdown-item
                >
                <el-dropdown-item command="-"
                  >减少手柄UI的大小（-/_）</el-dropdown-item
                >
                <el-dropdown-item command="x"
                  >x轴手柄是否显示（x）</el-dropdown-item
                >
                <el-dropdown-item command="y"
                  >y轴手柄是否显示（y）</el-dropdown-item
                >
                <el-dropdown-item command="z"
                  >z轴手柄是否显示（z）</el-dropdown-item
                >

                <el-dropdown-item command="c" divided
                  >透视相机/正交相机（c）</el-dropdown-item
                >
                <el-dropdown-item command="v"
                  >相机远近变换（v）</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button
            type="primary"
            size="small"
            icon="FullScreen"
            @click="onFullScreen"
          >
            {{ fullscreenStatus ? "取消全屏" : "全屏" }}
          </el-button>
        </el-space>
      </div>
    </header>
    <div class="model-container">
      <model-edit-panel></model-edit-panel>
      <!-- 模型视图 -->
      <model-view
        ref="modelViewRef"
        @dragover.prevent
        @drop="onDrop"
        :factoryId="props.factoryId"
      ></model-view>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  ref,
  getCurrentInstance,
  onBeforeUnmount,
  computed,
  watch,
} from "vue";
import * as THREE from "three";
import ModelEditPanel from "@/components/modelEditPanel/index.vue";
import ModelView from "@/components/model/ModelView.vue";
import { useMeshEditStore, formDataStore } from "@/stores/modules/model.js";
import { modelSubmitService, fileSubmitService } from "@/api/model.js";
import { useRouter } from "vue-router";
const { $bus } = getCurrentInstance().proxy;
const meshStore = useMeshEditStore();
const formStore = formDataStore();
const router = useRouter();

const props = defineProps({
  factoryId: {
    type: String,
    default: "",
  },
});
const modelViewRef = ref(null);

const uploadFile = async (param) => {
  var fileForm = new FormData();
  fileForm.append("blob", param.blob);
  const res = await fileSubmitService(fileForm);
  meshStore.addUploadModel({
    uuid: param.uuid,
    filename: res.data.data.filename,
    fileId: res.data.data.fileId,
  });
};
const onSubmitData = async () => {
  await modelViewRef.value.handleSubmit();

  var dataForm = {
    factoryId: props.factoryId,
    commonModels: formStore.commonModels,
    selfModels: formStore.selfModels,
    pipes: formStore.pipes,
    labels: formStore.labels,
  };

  const res = await modelSubmitService(dataForm);
  if (res.data.success) {
    ElMessage.success("上传成功！");
  }
};
const goBack = () => {
  router.push("/work/home/" + props.factoryId);
};
const onDownloadCover = () => $bus.emit("download-cover");
const onExportModleFile = (type) => $bus.emit("download-model", type);

// 添加模型
const onDrop = (e) => {
  const modelApi = meshStore.modelApi;
  const dragType = meshStore.dragType;
  const { clientX, clientY } = e;

  if (dragType === "models") {
    $bus.emit("add-model", {
      modelApi: modelApi,
      clientX: clientX,
      clientY: clientY,
    });
  } else if (dragType === "tags") {
    $bus.emit("add-label", {
      modelApi: modelApi,
      clientX: clientX,
      clientY: clientY,
    });
  }
};

// 全屏
const fullscreenStatus = ref(false);
const onFullScreen = () => {
  const element = document.documentElement;
  if (!fullscreenStatus.value) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
      // 适用于旧版WebKit浏览器
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
};
// 全屏监听事件
const addEventListenerFllscreen = (e) => {
  const status = document.fullscreenElement || document.webkitFullscreenElement;
  fullscreenStatus.value = !!status;
};

onMounted(() => {
  // 全屏监听事件
  document.addEventListener("fullscreenchange", addEventListenerFllscreen);
  // 上传文件
  $bus.on("upload-success", (param) => uploadFile(param));
});
onBeforeUnmount(() => {
  document.removeEventListener("fullscreenchange", addEventListenerFllscreen);
});
</script>

<style lang="scss" scoped>
.model-edit-panel {
  width: 10%;
}
.model-page {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f0f0f0;
  .operate-panel {
    height: 35px;
    width: 100%;
    background-color: #010c1d;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
    text-align: center;
    font-weight: 500;
    color: #fff;
    text-shadow: 5px 3px 5px #c11212;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0px 10px;
    box-sizing: border-box;
  }
  .model-container {
    display: flex;
    position: relative;
  }
}
</style>